<?php

namespace App\Http\Controllers\Title;

use Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\FirstLevel;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;

class AddFirstTitleController extends Controller
{


    public function index(Request $request)
    {
        try {
            $input = $request->all();
            $first_levels = FirstLevel::where('name', 'like', '%' . $input['search'] . '%')->orderBY('weight')->paginate($input['page_size']);
            return $this->success(200, $first_levels);
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }
    }

    public function store(Request $request)
    {
        if (Auth::user()->is_superuser) {
            $first_level = new FirstLevel;
            $first_level->level = 1;
            $first_level->name = $request->name;
            $first_level->weight = $request->weight;
            $first_level->type = $request->type;
            $first_level->url = $request->url;
            $first_level->save();
        } else {
            $this->fail(403, ['Message' => '权限不足']);
        }

    }

    public function update(Request $request, $id)
    {
        if (Auth::user()->is_superuser) {
            $first_level = FirstLevel::find($id);
            $first_level->name = $request->name;
            $first_level->weight = $request->weight;
            $first_level->type = $request->type;
            $first_level->url = $request->url;
            $first_level->save();
        } else {
            $this->fail(403, ['Message' => '权限不足']);
        }
    }

    public function show($id)
    {
        return FirstLevel::find($id);
    }

    public function destroy($id)
    {
        try {
            if (Auth::user()->is_superuser) {
                $first_level = FirstLevel::find($id);
                $first_level->delete();
                return $this->success(204);
            } else {
                $this->fail(403, ['Message' => '权限不足']);
            }
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }
    }

    public function getLevel()
    {
        try {
            $first_levels = FirstLevel::orderBY('weight')->get();
            foreach ($first_levels as $first_level) {
                $first_level->subMenu;
            }
            return $this->success(200, $first_levels);
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }

    }
}
